﻿using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace GenerateEntity.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }



        //链接数据库
        public JsonResult LinkServer(string Link)
        {
            ResultInfo result = new ResultInfo();
            try
            {
                //配置数据库连接
                SqlSugarClient db = new SqlSugarClient(
                                    new ConnectionConfig()
                                    {
                                        ConnectionString = "" + Link + ";database=master",
                                        DbType = DbType.SqlServer,//设置数据库类型
                                        IsAutoCloseConnection = true,//自动释放数据务，如果存在事务，在事务结束后释放
                                        InitKeyType = InitKeyType.Attribute //从实体特性中读取主键自增列信息
                                    });
                string sql = @"SELECT top 100000 Name FROM Master..SysDatabases ORDER BY Name";  //查询所有链接的所有数据库名
                var strList = db.SqlQueryable<databaseName>(sql).ToList();
                result.info = Newtonsoft.Json.JsonConvert.SerializeObject(strList);
                result.res = true;
                result.msg = "链接成功！";
            }
            catch (Exception ex)
            {
                result.msg = ex.Message;
            }

            return Json(result, JsonRequestBehavior.AllowGet);
        }

        //根据数据库名查询所有表
        public JsonResult GetTable(string Link, string Name)
        {

            ResultInfo result = new ResultInfo();
            try
            {
                //配置数据库连接
                SqlSugarClient db = new SqlSugarClient(
                                    new ConnectionConfig()
                                    {
                                        ConnectionString = "" + Link + ";database=" + Name + "",
                                        DbType = DbType.SqlServer,//设置数据库类型
                                        IsAutoCloseConnection = true,//自动释放数据务，如果存在事务，在事务结束后释放
                                        InitKeyType = InitKeyType.Attribute //从实体特性中读取主键自增列信息
                                    });

                string sql = @"SELECT top 10000 Name FROM SYSOBJECTS WHERE TYPE='U' ORDER BY Name";  //查询所有链接的所有数据库名
                var strList = db.SqlQueryable<databaseName>(sql).ToList();
                result.info = Newtonsoft.Json.JsonConvert.SerializeObject(strList);
                result.res = true;
                result.msg = "查询成功！";
            }
            catch (Exception ex)
            {
                result.msg = ex.Message;
            }

            return Json(result, JsonRequestBehavior.AllowGet);
        }

        //生成实体
        public JsonResult GenerateEntity(string Link, string Name, string TableName, string type)
        {

            ResultInfo result = new ResultInfo();
            try
            {
                //配置数据库连接
                SqlSugarClient db = new SqlSugarClient(
                                    new ConnectionConfig()
                                    {
                                        ConnectionString = "" + Link + ";database=" + Name + "",
                                        DbType = DbType.SqlServer,//设置数据库类型
                                        IsAutoCloseConnection = true,//自动释放数据务，如果存在事务，在事务结束后释放
                                        InitKeyType = InitKeyType.Attribute //从实体特性中读取主键自增列信息
                                    });

                string path = "C:\\Demo\\2";

                if (type == "0")
                {
                    path = "C:\\Demo\\2";
                    db.DbFirst.Where(TableName).CreateClassFile(path);
                    result.info = System.IO.File.ReadAllText(@"" + path + "\\" + TableName + ".cs" + "", Encoding.UTF8);
                }
                else if (type == "1")
                {
                    path = "C:\\Demo\\3";
                    db.DbFirst.IsCreateAttribute().CreateClassFile(path);
                    result.info = "";
                }



                result.res = true;
                result.msg = "生成成功！";
            }
            catch (Exception ex)
            {
                result.msg = ex.Message;
            }

            return Json(result, JsonRequestBehavior.AllowGet);
        }

        //生成全部表时查看
        public JsonResult GetGenerateEntity(string TableName)
        {

            ResultInfo result = new ResultInfo();
            try
            {
                string path = "C:\\Demo\\3";
                result.info = System.IO.File.ReadAllText(@"" + path + "\\" + TableName + ".cs" + "", Encoding.UTF8);
                result.res = true;
                result.msg = "查询成功！";
            }
            catch (Exception ex)
            {
                result.msg = ex.Message;
                try
                {
                    if (result.msg.Contains("未能找到文件"))
                    {
                        string path = "C:\\Demo\\2";
                        result.info = System.IO.File.ReadAllText(@"" + path + "\\" + TableName + ".cs" + "", Encoding.UTF8);
                        result.res = true;
                        result.msg = "查询成功！";
                    }
                }
                catch (Exception)
                {
                    result.msg = ex.Message;
                }
            }

            return Json(result, JsonRequestBehavior.AllowGet);
        }

        //数据库名
        public class databaseName
        {
            public string Name { get; set; }
        }

        //封装返回信息数据
        public class ResultInfo
        {
            public ResultInfo()
            {
                res = false;
                startcode = 449;
                info = "";
            }
            public bool res { get; set; }  //返回状态（true or false）
            public string msg { get; set; }  //返回信息
            public int startcode { get; set; }  //返回http的状态码
            public string info { get; set; }  //返回的结果（res为true时返回结果集，res为false时返回错误提示）
        }

    }
}